import React from 'react';
import { Button, Icon, message } from 'antd';
import cass from 'classnames';
import s from './index.module.less';
import { getTimeStringAutoShort } from '../../utils/util';
import sdk from '../../utils/imSdk';
import Avatar from '../Avatar';
import config from '../../config';
import taskServer from '../../services/task';
import projectServer from '../../services/project';
import isSuccess from '../../utils/error';

const { baseUrl } = config;
const { viewFile: pViewFile } = projectServer;
const { viewFile: tViewFile } = taskServer;

/**
 * 注意data:m的解析，因为获取聊天记录列表用的是后端保存的数据，实时聊天获取的是腾讯云的数据
*/
export default class ChatItem extends React.Component {

    onContextMenu = (text, m) => {
        const GroupId = m.groupid || m.getSession().id();
        const MsgSeq = m.msgseq || m.seq;
        const { extentNode, baseOffset, extentOffset } = window.getSelection();
        const nodeText = extentNode.data || text;
        const selText = nodeText.substring(baseOffset, extentOffset) || text; // 没选中默认全部内容
        const textValue = selText.replace(/[\r\n]/g, '');
        // 该事件的订阅放在/src/pages/dashboard/index.js文件，避免多次订阅
        const { ipcRenderer } = window.electron;
        ipcRenderer.send('show-right-click-menu', { show: ['copy', 'settask'], textValue, GroupId, MsgSeq });
    }

    renderMsg = ({ text, isCenter, isLocation, imgs, location, m }) => {
        if (isLocation) {
            return (
                <div className={s.map}>
                    <img src={imgs[0]} alt="location" />
                    <div className={s.localText}>
                        <h4>{location.address}</h4>
                        {location.street}
                    </div>
                </div>
            )
        };

        return (
            <div
                className={s.textContent}
                onContextMenu={() => this.onContextMenu(text, m)}
                ref={d => this.textContent = d}
            >
                {!isCenter ? text : null}
            </div>
        )
    }

    onViewFile = async ({ newfilename, text, filename, fileid }) => {
        if (window.isOpenPreviewItem) {
            message.warn('正在打开文件，请稍后...');
            return;
        }

        let fn = filename || text.split('文件:')[1];
        if (fn && fn.indexOf('到文件夹') > 0) {
            fn = text.split('到文件夹')[0];
        }

        const { isProject, projectid, taskid } = this.props;
        const res = await (isProject ? pViewFile : tViewFile)({ fileid });
        // 成功更新数据
        if (isSuccess(res)) {
            const ev = new CustomEvent(isProject ? 'refleshSideProject' : 'refleshSideTask', {    //第二个参数为ev事件对象添加的属性
                bubbles: 'true',
                cancelable: 'true',
                detail: isProject ? { projectid } : { taskid }
            });
            document.dispatchEvent(ev);
        }


        // 避免多次订阅，订阅打开应用的回调放在/src/pages/dashboard/index.js文件里面，添加isOpenPreviewItem标记正在打开
        window.isOpenPreviewItem = true;
        const { ipcRenderer } = window.electron;
        ipcRenderer.send("preview", { filename: fn, newfilename, url: `${baseUrl}/file/${newfilename}` });
    }

    render() {
        const { data: m } = this.props;
        const isBackendMsg = !!m.recid;
        const fromAccount = m.fromAccount || `${m.senderid}`;
        const fromAccountNick = m.fromAccountNick || m.sendername;
        const headImg = m.fromAccountHeadurl || m.headimage;
        const msgTime = m.time || m.msgtime;
        const direction = fromAccount === window.localStorage.getItem('userId') ? 'right' : 'left';
        const isRight = direction === 'right';
        const isLeft = direction === 'left';
        const isCenter = fromAccount === '1';
        const msgJson = isBackendMsg ? sdk.getBackendMsgText(m.msgcontent) : sdk.getMsgText(m.elems);
        const { text, type, newfilename } = msgJson;
        const isLocation = type === 'TIMLocationElem';
        return (
            <div
                className={cass(s.wrap, {
                    [s.left]: isLeft && !isCenter,
                    [s.right]: isRight,
                    [s.center]: isCenter,
                    [s.location]: isLocation
                })}
            >
                {!isCenter ? (
                    <Avatar username={fromAccountNick} headimage={headImg} noOrigin={!isBackendMsg} />
                ) : null}
                <div className={s.text}>
                    {isLeft && !isCenter ? <Icon type="caret-left" /> : null}
                    {this.renderMsg({ ...msgJson, isCenter, isLocation, m })}
                    {!isCenter ? (
                        <div className={s.msg}>{fromAccountNick}</div>
                    ) : null}
                    {isCenter ? [
                        <div key="time" className={s.time}>{getTimeStringAutoShort(msgTime * 1000, true)}</div>,
                        (<div key="text">
                            {
                                newfilename ?
                                    <Button type="link" onClick={() => this.onViewFile(msgJson)}>{text}</Button> :
                                    text
                            }
                        </div>)
                    ] : null}
                    {isRight ? <Icon type="caret-right" /> : null}
                </div>
            </div>
        )
    }
}